package com.zz.reflection;

import com.zz.Interface.studentMannger.ClassManager;
import org.junit.Test;

import java.lang.reflect.Field;

/**
 * 目标：获取类的成员变量，并对其操作
 */
public class Test3Field {
    @Test
    public void testGetFields() throws NoSuchFieldException, IllegalAccessException {
        //1.反射第一步，必须是先得到类的Class对象
        Class s = Student.class;

        //2.获取类的全部成员变量
        Field[] fields = s.getDeclaredFields();

        //3.遍历这个成员变量数组
        for (Field field : fields) {
            System.out.println(field.getName() + "==>" + field.getType());
        }
        //4.定位某个成员变量
        Field fName = s.getDeclaredField("name");
        System.out.println(fName.getName() + "===>" + fName.getType());

        //赋值
        Student student = new Student();
        fName.setAccessible(true);//禁止访问控制权限
        fName.set(student, "小红");
        System.out.println(student);

        //取值
        String name = (String)fName.get(student);
        System.out.println(name);
    }
}
